import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shake_animation_widget/shake_animation_widget.dart';

class BlindBoxUi extends StatefulWidget {
  const BlindBoxUi({Key? key}) : super(key: key);

  @override
  State<BlindBoxUi> createState() => _BlindBoxUiState();
}

class _BlindBoxUiState extends State<BlindBoxUi> {

  late Size _size;
  late double _screenWidth;
  late double _screenHeight;
  int _boxCount = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getRaminCount();
  }

  @override
  Widget build(BuildContext context) {
    _size = MediaQuery.of(context).size;
    _screenWidth = _size.width;
    _screenHeight = _size.height;
    final bgHeight = _screenWidth / 750 * 1334;
    final ratio = bgHeight / 1334;
    return Container(
      color: const Color(0xFFFD8376),
      child: Stack(
        children: [
          Image.asset(
            "images/ic_mhb.png",
            width: _screenWidth,
            height: bgHeight,
          ),
          // Positioned(
          //   bottom: 0,
          //   child: Container(
          //     height: 800,
          //     width: _screenWidth,
          //     decoration: const BoxDecoration(
          //         gradient: LinearGradient(
          //             colors: [Color(0xFFFD8376), Color(0x00FFFFFF)],
          //             begin: Alignment.bottomCenter,
          //             end: Alignment.topCenter
          //         )
          //     ),
          //     ),
          // ),
          Positioned(
            left: 113 * ratio,
            top: 451 * ratio,
            child: ShakeAnimationWidget(
              child: Image.asset(
                "images/ic_mhz.png",
                width: 557 * ratio,
                height: 392 * ratio,
              ),
              shakeAnimationType: ShakeAnimationType.RoateShake,
              isForward: false,
              shakeCount: 0,
            ),
          ),
          Positioned(
            left: 210 * ratio,
            top: 1006 * ratio,
            child: GestureDetector(
              onTap: () async{
                if (_boxCount == 0) {
                  final res = _purchase();
                } else {
                  _openBlindBox();
                }
              },
              child: Image.asset(
                "images/ic_${_boxCount == 0 ? 'mgm' : 'mcq'}.png",
                width: 327 * ratio,
                height: 93.5 * ratio,
              ),
            ),
          ),
          Positioned(
            top: 1136 * ratio,
            width: _screenWidth,
            child: Align(
              alignment: Alignment.center,
              child: Text(
                "剩余$_boxCount次机会",
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 14
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  /// 获取盲盒剩余次数
  _getRaminCount() async {
    final res = await Api.getInstance().getBlindBoxRemainCount();
    if (res['code'] == 0) {
      print(res['data']);
      // {availableCount: 0, usedCount: 0}
      final data = res['data'];
      int availableCount = data['availableCount'];
      int usedCount = data['usedCount'];
      setState(() {
        _boxCount = availableCount;
      });
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  /// 打开盲盒
  _openBlindBox() async {
    final res = await Api.getInstance().openBlindBox();
    if (res['code'] == 0) {
      print(res['data']);
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  /// say hi
  _sayHi(String hi, String openId) async {
    final res = await Api.getInstance().hiBlindBox(hi, openId);
    if (res['code'] == 0) {
      print(res['data']);
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  /// 购买
  _purchase() async {
    final positionHeight = (_screenWidth - 48) / 3 / 110 * 65;
    return showModalBottomSheet<int>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: positionHeight + 168,
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12.0),
              topRight: Radius.circular(12.0),
            ),
          ),
          child: Column(
            children: [
              Container(
                alignment: Alignment.center,
                height: 56,
                child: Text(
                  "充值盲盒",
                  style: TextStyle(
                      color: ThemeColor.textColor,
                      fontSize: 16
                  ),
                ),
              ),
              const SizedBox(height: 12,),
              SizedBox(
                height: positionHeight,
                child: ListView.builder(
                    itemCount: 3,
                    scrollDirection: Axis.horizontal,
                    itemBuilder: (ctx, index) {
                      return _buildPurchaseItem(index, index * 10);
                    }
                ),
              ),
              Container(
                height: 40,
                margin: const EdgeInsets.fromLTRB(12, 25, 12, 8),
                decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20)
                  ),
                  color: ThemeColor.mainColor,
                ),
                alignment: Alignment.center,
                child: const Text(
                  "立即充值",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 15
                  ),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("充值代表已阅读并同意", style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 12),),
                  GestureDetector(
                    onTap: () {

                    },
                    child: const Text(
                      "《用户充值协议》",
                      style: TextStyle(
                          fontSize: 12,
                          color: Color(0xFF03488D)
                      ),
                    ),
                  )
                ],
              )
            ],
          )
        );
      },
    );
  }

  double _checkMoney = 0;
  Widget _buildPurchaseItem(int count, double money) {
    final itemWidth =  (_screenWidth - 48) / 3;
    final itemHeight = itemWidth / 110 * 65;
    return GestureDetector(
      onTap: () {
        setState(() {
          _checkMoney = money;
        });
      },
      child: Container(
          width: itemWidth,
          height: itemHeight,
          margin: const EdgeInsets.only(left: 12),
          alignment: Alignment.center,
          decoration: ShapeDecoration(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8)
              ),
              color: const Color(0xFFF8F8F7)
          ),
          child: Text.rich(TextSpan(
              children: [
                TextSpan(
                    text: "$count",
                    style: TextStyle(
                        color: ThemeColor.textColor,
                        fontSize: 18
                    )
                ),
                TextSpan(
                    text: "盲盒",
                    style: TextStyle(
                      color: ThemeColor.textColor,
                      fontSize: 13,
                    )
                ),
                TextSpan(
                    text: "\n$money元",
                    style: TextStyle(
                        color: ThemeColor.textColorSecond,
                        fontSize: 13
                    )
                )
              ]
          ),)
      ),
    );
  }

}
